package com.ygqh.baby.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.constant.Constant;
import com.ygqh.baby.mapper.YgUserMemberMapper;
import com.ygqh.baby.model.UserMemberModel;
import com.ygqh.baby.model.VipCoupon;
import com.ygqh.baby.po.*;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.*;
import com.ygqh.baby.utils.DateConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;

@Service
public class YgUserMemberServiceImpl implements YgUserMemberService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private YgUserMemberMapper ygUserMemberMapper;
    @Autowired
    private RedisDao redisDao;
    @Autowired
    private YgUserService ygUserService;
    @Autowired
    private YgFrameCodeService ygFrameCodeService;
    @Autowired
    private YgCardCouponDetailService ygCardCouponDetailService;
    @Autowired
    private YgCardCouponService ygCardCouponService;
    @Autowired
    private YgCouponService ygCouponService;
    @Autowired
    private WxMpMessageService wxMpMessageService;
    @Autowired
    private YgRechargeMemberRecordService ygRechargeMemberRecordService;
    @Autowired
    private YgAgentInviteRecordService ygAgentInviteRecordService;
    @Autowired
    private YgUserBalanceService ygUserBalanceService;

    @Override
    public List<YgUserMember> find() {
        YgUserMemberExample example = new YgUserMemberExample();
        example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
        return ygUserMemberMapper.selectByExample(example);
    }

    @Override
    public int findCount() {
        YgUserMemberExample example = new YgUserMemberExample();
        example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
        return ygUserMemberMapper.countByExample(example);
    }

    @Override
    public YgUserMember findById(Long id) {
        return ygUserMemberMapper.selectByPrimaryKey(id);
    }

    @Override
    public int save(YgUserMember ygUserMember) {
        return ygUserMemberMapper.insertSelective(ygUserMember);
    }

    @Override
    public int update(YgUserMember ygUserMember) {
        return ygUserMemberMapper.updateByPrimaryKeySelective(ygUserMember);
    }

    @Override
    public ResultSet<YgUserMember> search(QueryInfo queryInfo, String q, String nickName) {
        List<YgUserMember> list = ygUserMemberMapper.selectSuper(queryInfo, q, nickName);
        int count = ygUserMemberMapper.countSuper(q, nickName);
        ResultSet<YgUserMember> resultSet = new ResultSet<YgUserMember>(count, list);
        return resultSet;
    }

    @Override
    public int deleteSoft(Long[] ids) {
        Assert.notEmpty(ids);
        YgUserMemberExample example = new YgUserMemberExample();
        example.createCriteria().andIdIn(Arrays.asList(ids));
        YgUserMember record = new YgUserMember();
        record.setStatus(DataStatus.Delete);

        return ygUserMemberMapper.updateByExampleSelective(record, example);
    }

    @Override
    public int deleteSoft(Long id) {
        return this.deleteSoft(new Long[]{id});
    }

    @Override
    public int saveOrUpdate(YgUserMember ygUserMember) {
        int r = 0;
        if (ygUserMember.getId() != null) {
            r = this.update(ygUserMember);
        } else {
            r = this.save(ygUserMember);
        }
        return r;
    }

    @Override
    public int becomeToMember(Long userId, Date startTime, Date endTime, Date birthDay) {

        YgUserMember member = this.findByUserId(userId);
        if (member == null) {
            member = new YgUserMember(userId, startTime, endTime);
            member.setCreateBy("sys");
            member.setCreateTime(new Date());
            this.save(member);
        } else {
            member.setMemberStartTime(startTime);
            if (member.isMembersValid()) {
                endTime = DateConvertUtils.addYear(member.getMemberEndTime(), 1);
            }
            member.setMemberEndTime(endTime);
            member.setUpdateBy("sys");
            member.setUpdateTime(new Date());
            this.update(member);
        }
        ygUserService.updateUserLevel(userId, 10, birthDay);
        return 1;
    }

    @Override
    public int becomeToMember(Long userId, Date startTime, Date endTime, String sourceCode) {

        YgUserMember member = this.findByUserId(userId);
        YgUser inviter = ygUserService.findBySourceCode(sourceCode);
        if (member == null) {

            member = new YgUserMember(userId, startTime, endTime);
            member.setCreateBy("sys");
            member.setCreateTime(new Date());
            member.setUpdateTime(member.getCreateTime());
            member.setUpdateBy("sys");
            member.setInviterId(inviter == null ? userId : inviter.getId());
            this.save(member);
        } else {
            if (member.isMembersValid()) {
                endTime = DateConvertUtils.addYear(member.getMemberEndTime(), 1);
            } else {
                member.setMemberStartTime(startTime);
            }
            if (member.getInviterId().compareTo(member.getUserId()) == 0) {
                member.setInviterId(inviter == null ? userId : inviter.getId());
            }
            member.setMemberEndTime(endTime);
            member.setUpdateBy("sys");
            member.setUpdateTime(new Date());
            this.update(member);

            /*List<YgAgentInviteRecord> agentRecord = ygAgentInviteRecordService.findByReceiveUserId(userId);
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(agentRecord)) {
                YgAgentInviteRecord record = agentRecord.get(0);
                record.setExpireTime(member.getMemberEndTime());
                record.setUserId(member.getInviterId());
                if (member.getInviterId() != null) {
                    YgUser ygUser = ygUserService.findById(member.getInviterId());
                    record.setUserName(ygUser.getUserName());
                }
                ygAgentInviteRecordService.update(record);
            }*/

        }
        ygUserService.updateUserLevel(userId, 10, null);
        if (inviter != null && UserType.UserAgent.equals(inviter.getUserType())) {
            ygUserBalanceService.incomeRecharge(inviter.getId(), new BigDecimal(100), OperationType.PullNewVip, userId.toString(), "邀请女王充值奖励", "system");
        }
        return 1;
    }

    @Override
    public YgUserMember findByUserId(Long userId) {
        Assert.notNull(userId);
        YgUserMemberExample example = new YgUserMemberExample();
        example.createCriteria().andUserIdEqualTo(userId);
        List<YgUserMember> list = ygUserMemberMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public Boolean isVip(Long userId) {
        return ygUserMemberMapper.isVip(userId);
    }

    @Override
    public BigDecimal getVipPrice() {
        BigDecimal vipPrice = null;
        String vipMap = redisDao.get("vipprice");
        if (StringUtils.isNotBlank(vipMap)) {
            @SuppressWarnings("unchecked") Map<String, BigDecimal> map = JSONObject.parseObject(vipMap, Map.class);
            vipPrice = new BigDecimal(map.get("vipPrice") + "");
        }
        return vipPrice;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Map<String, BigDecimal> getMapVipPrice() {
        Map<String, BigDecimal> map = new HashMap<String, BigDecimal>();
        String vipMap = redisDao.get("vipprice");
        if (StringUtils.isNotBlank(vipMap)) {
            map = JSONObject.parseObject(vipMap, Map.class);

        }
        return map;
    }

    @Override
    public VipCoupon getVipCoupon() {
        String couponInfo = redisDao.get("vipcoupon");
        Map<String, String> map = JSON.parseObject(couponInfo, Map.class);
        String idsStr = map.get("couponBatchIds");
        Long quantity = Long.parseLong(map.get("quantity"));
        String[] split = idsStr.split(",");
        List<Long> ids = new ArrayList<Long>();
        for (String id : split) {
            ids.add(Long.parseLong(id));
        }

        return new VipCoupon(ids.toArray(new Long[ids.size()]), quantity);
    }

    @Override
    public int becomeToMemberNotPay(String cardIds, YgUser user, Date birthDay) {

        if (ygUserService.isVipNew(user.getId(), Constant.YIIGOO_PLATFORM_NO)) {
            return 0;
        }
        // 设置用户表登记，会员表有效期
        Date currentDate = new Date();
        Date endTime = DateConvertUtils.addYear(currentDate, 1);
        this.becomeToMember(user.getId(), currentDate, endTime, birthDay);

        Long paymentCode = ygFrameCodeService.getFrameCode(CodeType.RechargeMB, new Date());
        // 添加明细表
        BigDecimal zero = new BigDecimal("0.00");
        YgRechargeMemberRecord memberRecord = new YgRechargeMemberRecord();
        memberRecord.setUserId(user.getId());
        memberRecord.setPaymentCode(paymentCode);
        memberRecord.setMemberPrice(zero);
        memberRecord.setMemberType("year");
        memberRecord.setPaidPrice(zero);
        memberRecord.setPaidTime(new Date());
        memberRecord.setTransactionId(paymentCode.toString());
        memberRecord.setPayType(PayType.WeChat);
        memberRecord.setCreateTime(new Date());

        ygRechargeMemberRecordService.save(memberRecord);
        user.setLevel(10);
        this.sendQueenCoupon(user);
        // 生成卡券
        ygCardCouponDetailService.generateCardCouponBatch(user.getId(), cardIds, paymentCode, "becomeToMemberNotPay");
        return 1;
    }

    private final String cardKeyPrefix = "default_card_key";

    @Override
    public Message sendQueenCoupon(YgUser user) {

        try {
            List<YgCardCoupon> list = ygCardCouponService.findCardsByMonth(CardType.BasicsGift, CardMode.Coupon, new Date());
            if (CollectionUtils.isEmpty(list)) {
                String hget = redisDao.hget(cardKeyPrefix, CardType.BasicsGift.name());
                if (StringUtil.isNotBlank(hget)) {
                    YgCardCoupon card = JSON.parseObject(hget, YgCardCoupon.class);
                    if (card.getCardMode().equals(CardMode.Coupon)) {
                        list = Collections.singletonList(card);
                    }
                }
            }
            for (YgCardCoupon card : list) {
                this.sendQueenCoupon(user, card.getCouponId());

            }
        } catch (Exception e) {
            logger.error("发送女王券失败。userId:{},错误信息：{}", user.getId(), e.getMessage());
            e.printStackTrace();
        }
        return Message.success(null);
    }

    @Override
    public Message sendQueenCoupon(YgUser user, Long couponBatchId) {

        // 给会员券
        YgCoupon coupon = ygCouponService.findById(couponBatchId);

        //		Date start = new Date();
        for (int i = 0; i < coupon.getLeadNum(); i++) {
            ygCouponService.receiveCoupon(couponBatchId, user);
        }

        //		String first = "女王,优惠券已奉上,请查收！";
        //		String link = "/user/coupon.html";
        //		String remark = "到我的优惠券看看吧。";
        //		String[] keyword = new String[] { user.getUserName(), "有效期 " + DateConvertUtils.format(start) + "至" + DateConvertUtils.format(end) };
        //		wxMpMessageService.sendBindMsg(first, link, remark, user, keyword);

        return Message.success(null);
    }

    @Override
    public ResultSet<YgUserMember> searchCountVip(QueryInfo queryInfo) {
        List<YgUserMember> list = ygUserMemberMapper.selectCountVip(queryInfo);
        int count = ygUserMemberMapper.countVip();
        ResultSet<YgUserMember> resultSet = new ResultSet<YgUserMember>(count, list);
        return resultSet;
    }

    @Override
    public void transferMember(YgUser sourceUser, YgUser targetUser) {
        if (sourceUser.getLevel() == 10 && targetUser.getLevel() != 10) {
            ygUserService.updateUserLevel(targetUser.getId(), sourceUser.getLevel(), sourceUser.getBabyBirthday());
            YgUserMember sourceMember = this.findByUserId(sourceUser.getId());
            if (sourceMember != null) {
                sourceMember.setUserId(targetUser.getId());
                sourceMember.setId(null);
                this.save(sourceMember);
            }
            YgRechargeMemberRecord record = ygRechargeMemberRecordService.findPaySuccessRecordByUserId(sourceUser.getId());
            if (record != null) {
                record.setId(null);
                record.setUserId(targetUser.getId());
                ygRechargeMemberRecordService.save(record);
            }
        }
    }

    @Override
    public List<UserMemberModel> findUserByEndDate(Date minEndDate, Date maxEndDate) {
        return ygUserMemberMapper.selectUserByEndDate(minEndDate, maxEndDate);
    }
}
